package com.aijk.commons.jaxb;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Jaxb 日期格式化 yyyy-MM-dd HH:mm:ss
 * User: chendw
 * Date: 2016/8/8 12:02
 * To change this template use File | Settings | File Templates.
 */
public abstract class JaxbAbstractDateAdapter extends XmlAdapter<String, Date> {

    /**
     * 字符串转日期
     *
     * @param dateStr 日期字符串
     * @return
     * @throws Exception
     */
    @Override
    public Date unmarshal(String dateStr) throws Exception {
        if (dateStr == null) {
            return null;
        }

        DateFormat format = new SimpleDateFormat(getDateFormat());
        return format.parse(dateStr);
    }

    /**
     * 日期格式为字符串
     *
     * @param date
     * @return
     * @throws Exception
     */
    @Override
    public String marshal(Date date) throws Exception {
        DateFormat format = new SimpleDateFormat(getDateFormat());
        return format.format(date);
    }

    /**
     * 日期格式
     *
     * @return
     */
    public abstract String getDateFormat();
}
